<template>
  <div>
    <a-row :gutter="20"><a-col :span="14">
        <!-- 仪器串组合推荐 -->
        <a-spin :spinning="spinning">
          <a-row>
            <a-button type="dashed" style="width: 50%" @click="addCombSuggest" :disabled="!combSuggestListQuery.schemeId">
              <template #icon><node-index-outlined /></template>选择第 {{ numberOfPasses }} 趟组合
            </a-button>
            <a-button type="dashed" style="width: 50%" @click="openCraft" :disabled="!combSuggestListQuery.schemeId">
              <template #icon>
                <SlidersOutlined />
              </template>选择施工工艺
            </a-button>
          </a-row>
          <a-table :pagination="false" :columns="combinationColumns" :data-source="combSuggestData">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.title === '仪器串组合'">
                {{ record.instrumentCombination.toString().replace(/,/g, " + ") }}
              </template>
              <template v-if="column.dataIndex === 'operation'">
                <a-button @click="updateCombSuggest(record)">修改 </a-button>
                <a-button style="margin-left: 10px" @click="delCombSuggest(record.id)">删除 </a-button>
              </template>
            </template>
          </a-table>
          <a-table :pagination="false" :showHeader="false" :columns="instrumentListColumns" :data-source="instrumentList">
            <template #title>{{ instrumentTableTitle }}</template>
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'operation'">
                <a-popconfirm title="请选择在下方或在上方插入" ok-text="向下" cancel-text="向上"
                  @confirm="insertToDown(record.instrumentId)" @cancel="insertToUp(record.instrumentId)">
                  <a-button style="margin-left: 30px">插入 </a-button>
                </a-popconfirm>
                <a-button style="margin-left: 10px" @click="delInstrument(record)"> 删除 </a-button>
              </template>
            </template>
          </a-table></a-spin>
      </a-col>
      <a-col :span="10">
        <a-spin :spinning="spinning">
          <div ref="d3CanvasRef">
            <canvasIns :data="instrumentList"></canvasIns>
          </div>
        </a-spin> </a-col></a-row>
  </div>
  <!-- 选择仪器串推荐组合弹窗 -->
  <AntdConfirmModal :showConfirm="false" :title="modalTitle" ref="combSuggestModalRef" width="1200px">
    <a-spin :spinning="spinning">
      <instrument-combination-radio @combSuggestSelection="combSuggestSelection"></instrument-combination-radio></a-spin>
  </AntdConfirmModal>
  <!-- 选择仪器弹窗 -->
  <AntdConfirmModal @confirm="submitUpdateForm" :title="modalTitle" ref="instrumentModalRef" width="1200px">
    <a-spin :spinning="spinning">
      <a-row style="margin-bottom: 10px">
        <a-select ref="select" v-model:value="optionType" style="width: 120px">
          <a-select-option value="instrument">仪器信息</a-select-option>
          <a-select-option value="horsehead">马笼头</a-select-option>
        </a-select></a-row>
      <horsehead-popup v-if="optionType === 'horsehead'" @horseheadSelection="horseheadSelection"></horsehead-popup>
      <instrument-popup v-if="optionType === 'instrument'"
        @instrumentSelection="instrumentSelection"></instrument-popup></a-spin>
  </AntdConfirmModal>
  <craftt-drawer ref="crafttDrawerRef"></craftt-drawer>
</template>
<script setup>
import useApp from "@/hooks";
import canvasIns from "./canvas.vue";
import html2canvas from "html2canvas";
import InstrumentCombinationRadio from "./type/CombRadio.vue";
import CrafttDrawer from "./drawer/InstrumentDrawer.vue";
import InstrumentPopup from "./type/InstrumentPopup.vue";
import HorseheadPopup from "./type/HorseheadPopup.vue";
import { NodeIndexOutlined, SlidersOutlined } from "@ant-design/icons-vue";
import { cloneDeep } from "lodash-es";
import WellInstruments from '@/api/tool/instrument.js'
import WellHorsehead from "@/api/tool/horsehead.js";
import SchemeInstrument from '@/api/design/instString.js'
import WellCombination from "@/api/tool/combination.js";
const { $, proxy } = useApp();
const spinning = ref(false);
const d3CanvasRef = ref(null);
const crafttDrawerRef = ref(null);
const modalTitle = ref(null);
const instrumentId = ref(null);
const combSuggestModalRef = ref(null);
const instrumentModalRef = ref(null);
const instrumentTableTitle = ref(null);
const optionType = ref("instrument");
const numberOfPasses = ref(1);
const instrumentList = ref([]);
const combSuggestData = ref([]);
const instrumentSelectionData = ref([]);
const horseheadSelectionData = ref([]);
const editinstrumentTableList = reactive({});
//仪器串组合推荐表内容
const combinationColumns = ref([
  {
    dataIndex: "numbers",
    title: "趟次",
    width: 80,
  },
  {
    title: "仪器串组合",
    dataIndex: "instrumentCombination",
    key: "instrumentCombination",
  },
  {
    title: "操作",
    dataIndex: "operation",
    key: "operation",
    width: 200,
  },
]);
const instrumentListColumns = ref([
  {
    dataIndex: "instrumentId",
    width: 100,
  },
  {
    dataIndex: "instrumentName",
  },
  {
    dataIndex: "operation",
    fixed: "right",
    width: 230,
  },
]);
//仪器串推荐列表负载内容
const combSuggestListQuery = ref({
  schemeId: localStorage.getItem("schemeId"),
  order: "ASC",
  pageNum: 1,
  pageSize: 100,
  searchKey: undefined,
  sortBy: "numbers",
});
//仪器串推荐更新/新建负载内容
const combSuggesQuery = ref({});
//打开施工工艺抽屉
const openCraft = () => {
  crafttDrawerRef.value.openDrawer();
};
//打开添加仪器串组合推荐弹窗
const addCombSuggest = () => {
  modalTitle.value = `选择第 ${numberOfPasses.value} 趟组合`;
  combSuggestModalRef.value.openModal();
};
//删除仪器串组合推荐
const delCombSuggest = (key) => {
  spinning.value = true;
  SchemeInstrument.deleteOne(key)
    .then((res) => {
      instrumentList.value = [];
      instrumentTableTitle.value = undefined;
      $.showToast({
        title: "删除成功",
        icon: "success",
      });
      spinning.value = false;
      getCombSuggestDataList();
    })
    .catch((err) => {
      spinning.value = false;
    });
};
//更新仪器串组合推荐插入仪器
const insert = (key) => {
  editinstrumentTableList[key] = cloneDeep(instrumentList.value.filter((item) => key === item.instrumentId)[0]);
};
const insertToDown = (id) => {
  modalTitle.value = "选择向下插入的仪器";
  instrumentId.value = id;
  instrumentModalRef.value.openModal();
};
const insertToUp = (id) => {
  modalTitle.value = "选择向上插入的仪器";
  instrumentId.value = id;
  instrumentModalRef.value.openModal();
};
//更新仪器串组合推荐（修改按钮）
const updateCombSuggest = (record) => {
  spinning.value = true;
  combSuggesQuery.value = record;
  console.log(record);
  instrumentTableTitle.value = `第 ${record.numbers} 趟仪器串组合推荐`;
  const horseIndex = record.instrumentCombination.findIndex((element) => element.includes("马笼头"));
  const allInstrumentIdList = JSON.parse(JSON.stringify(record.instrumentIdList));
  const horseIdList = allInstrumentIdList.splice(horseIndex, 1);
  const instrumentContentList = [];
  const horseList = [];
  const promises = allInstrumentIdList.map((id) => WellInstruments.queryOne(id));
  Promise.all(promises).then((results) => {
    // results 数组包含了按照请求顺序返回的数据
    results.forEach((res) => {
      instrumentContentList.push(res);
    });
  });
  horseIdList.forEach((id) => {
    WellHorsehead.getOne(id).then((res) => {
      res.instrumentId = res.horseheadId;
      res.outerDiameter = res.maxDiameter;
      res.instrumentName = res.horseheadName;
      res.weight = 0;
      horseList.push(res);
    });
  });
  setTimeout(() => {
    instrumentList.value = [...horseList, ...instrumentContentList];
    spinning.value = false;
  }, 300);
};
//选择仪器
function instrumentSelection(e) {
  instrumentSelectionData.value = e;
}
//选择马笼头
function horseheadSelection(e) {
  horseheadSelectionData.value = e;
}
//删除仪器
function delInstrument(e) {
  spinning.value = true;
  instrumentList.value = instrumentList.value.filter((item) => item.id !== e.id);
  combSuggesQuery.value.instrumentCombination = combSuggesQuery.value.instrumentCombination.filter(
    (item) => item !== e.instrumentName
  );
  combSuggesQuery.value.instrumentIdList = combSuggesQuery.value.instrumentIdList.filter((item) => item !== e.id);
  combSuggesQuery.value.loggingContent = combSuggesQuery.value.loggingContent.filter(
    (item) => item !== e.loggingContent
  );
  combSuggesQuery.value.maxOuterDiameter = combSuggesQuery.value.maxOuterDiameter;  //最大外径*
  combSuggesQuery.value.totalLength = (combSuggesQuery.value.totalLength - e.length).toFixed(2);
  combSuggesQuery.value.totalWeight = (combSuggesQuery.value.totalWeight - e.weight).toFixed(2);
  console.log(combSuggesQuery.value);
  console.log(e);
  setTimeout(() => {
    html2canvas(d3CanvasRef.value).then((canvas) => {
      const imageData = canvas.toDataURL("image/png");
      combSuggesQuery.value.file = imageData;
      SchemeInstrument.updateOne(combSuggesQuery.value)
        .then((res) => {
          $.showToast({
            title: "删除成功",
            icon: "success",
          });
          spinning.value = false;
          getCombSuggestDataList();
        })
        .catch((err) => {
          spinning.value = false;
        });
    });
  }, 1000);
}
//修改推荐仪器串系列
function submitUpdateForm() {
  spinning.value = true;
  combSuggesQuery.value.loggingContent = [];
  combSuggesQuery.value.instrumentIdList = [];
  combSuggesQuery.value.instrumentCombination = [];
  combSuggesQuery.value.totalLength = 0;
  combSuggesQuery.value.maxOuterDiameter = 0;
  combSuggesQuery.value.totalWeight = 0;
  let array = [...horseheadSelectionData.value, ...instrumentSelectionData.value];
  if (instrumentId.value !== null) {
    let index = instrumentList.value.findIndex((item) => item.instrumentId == instrumentId.value);
    const position = modalTitle.value === "选择向上插入的仪器" ? 0 : 1;
    instrumentList.value.splice(index + position, 0, ...array);
    instrumentList.value = [...instrumentList.value];
    instrumentId.value = null;
  }
  instrumentList.value.forEach((e) => {
    // 如果有，将马笼头仪器参数名称与其他仪器参数名称统一
    if (e.hasOwnProperty("horseheadId")) {
      e.instrumentId = e.horseheadId;
      e.outerDiameter = e.maxDiameter;
      e.instrumentName = e.horseheadName;
      e.weight = 0;
    }
    //为修改仪器串推荐负载参数赋值
    combSuggesQuery.value.maxOuterDiameter =
      combSuggesQuery.value.maxOuterDiameter > e.outerDiameter
        ? combSuggesQuery.value.maxOuterDiameter
        : e.outerDiameter;
    combSuggesQuery.value.totalLength = combSuggesQuery.value.totalLength + e.length;
    combSuggesQuery.value.totalWeight = combSuggesQuery.value.totalWeight + e.weight;
    combSuggesQuery.value.loggingContent.push(e.loggingContent);
    combSuggesQuery.value.instrumentIdList.push(e.id);
    combSuggesQuery.value.instrumentCombination.push(e.instrumentName);
  });
  combSuggesQuery.value.totalWeight = combSuggesQuery.value.totalWeight.toFixed(2);
  combSuggesQuery.value.totalLength = combSuggesQuery.value.totalLength.toFixed(2);
  setTimeout(() => {
    html2canvas(d3CanvasRef.value).then((canvas) => {
      const imageData = canvas.toDataURL("image/png");
      combSuggesQuery.value.file = imageData;
      SchemeInstrument.updateOne(combSuggesQuery.value)
        .then((res) => {
          instrumentSelectionData.value = [];
          horseheadSelectionData.value = [];
          instrumentModalRef.value.closeModal();
          $.showToast({
            title: "修改成功",
            icon: "success",
          });
          spinning.value = false;
          getCombSuggestDataList();
        })
        .catch((err) => {
          spinning.value = false;
        });
    });
  }, 1000);
}
//添加仪器串组合推荐
function combSuggestSelection(item) {
  spinning.value = true;
  //查询仪器串包含的仪器所有信息
  WellCombination.getOne(item.id).then((res) => {
    combSuggesQuery.value.loggingContent = [];
    combSuggesQuery.value.instrumentIdList = [];
    combSuggesQuery.value.totalLength = 0;
    combSuggesQuery.value.maxOuterDiameter = 0;
    combSuggesQuery.value.totalWeight = 0;
    // 查找是否含有马笼头
    res.forEach((e) => {
      // 如果有，将马笼头仪器参数名称与其他仪器参数名称统一
      if (e.hasOwnProperty("horseheadId")) {
        e.instrumentId = e.horseheadId;
        e.outerDiameter = e.maxDiameter;
        e.instrumentName = e.horseheadName;
        e.weight = 0;
      }
      //为新建仪器串推荐负载参数赋值
      combSuggesQuery.value.maxOuterDiameter =
        combSuggesQuery.value.maxOuterDiameter > e.outerDiameter
          ? combSuggesQuery.value.maxOuterDiameter
          : e.outerDiameter;
      combSuggesQuery.value.totalLength = combSuggesQuery.value.totalLength + e.length;
      combSuggesQuery.value.totalWeight = combSuggesQuery.value.totalWeight + e.weight;
      combSuggesQuery.value.loggingContent.push(e.loggingContent);
      combSuggesQuery.value.instrumentIdList.push(e.id);
    });
    combSuggesQuery.value.instrumentCombination = item.instrumentNameList;
    combSuggesQuery.value.totalWeight = combSuggesQuery.value.totalWeight.toFixed(2);
    combSuggesQuery.value.totalLength = combSuggesQuery.value.totalLength.toFixed(2);
    combSuggesQuery.value.numbers = numberOfPasses.value;
    combSuggesQuery.value.schemeId = localStorage.getItem("schemeId");
    instrumentList.value = res;
    setTimeout(() => {
      html2canvas(d3CanvasRef.value).then((canvas) => {
        const imageData = canvas.toDataURL("image/png");
        combSuggesQuery.value.file = imageData;
        SchemeInstrument.createOne(combSuggesQuery.value)
          .then((res) => {
            combSuggestModalRef.value.closeModal();
            combSuggesQuery.value = res;
            $.showToast({
              title: "添加成功",
              icon: "success",
            });
            getCombSuggestDataList();
            spinning.value = false;
          })
          .catch((err) => {
            spinning.value = false;
          });
      });
    }, 1000);
  });
}
//获取已选择的仪器串推荐数据
function getCombSuggestDataList() {
  if (combSuggestListQuery.value.schemeId) {
    SchemeInstrument.queryList(combSuggestListQuery.value).then((res) => {
      combSuggestData.value = res.content;
      numberOfPasses.value = res.totalElements + 1;
    });
  } else {
    $.showToast({
      title: "无测井记录",
      icon: "warning",
    });
  }
}
getCombSuggestDataList();
</script>
